#include "dialog_admin.h"
#include "ui_dialog_admin.h"
#include "admsql.h"
#include <qmessagebox.h>

Dialog_password::Dialog_password(const AdmInfo& currentAdmin, AdmSql* admSql, QWidget* parent)
    : QDialog(parent)
    , ui(new Ui::Dialog_password)
    , m_currentAdmin(currentAdmin)  // 接收并存储 currentAdmin
    , m_admSql(admSql)
{
    ui->setupUi(this);
    ui->le_aname->setText(m_currentAdmin.aname);
    ui->le_email->setText(m_currentAdmin.email);
}
Dialog_password::~Dialog_password()
{
    delete ui;
}


void Dialog_password::on_pb_save_2_clicked()
{
    QString oldPassword = ui->le_password1->text().trimmed();
    QString newPassword = ui->le_password2->text().trimmed();
    QString confirmPassword = ui->le_password3->text().trimmed();
    QString aname = ui->le_aname->text().trimmed(); // 获取账户名
    QString email = ui->le_email->text().trimmed(); // 获取邮箱

    // 验证输入
    if (oldPassword.isEmpty() || newPassword.isEmpty() || confirmPassword.isEmpty() || aname.isEmpty() || email.isEmpty()) {
        QMessageBox::warning(this, tr("输入错误"), tr("输入不能为空！"));
        return;
    }

    // 验证新密码和确认密码是否匹配
    if (newPassword != confirmPassword) {
        QMessageBox::warning(this, tr("密码不匹配"), tr("新密码与确认密码不匹配！"));
        return;
    }

    // 更新管理员信息
    m_currentAdmin.aname = aname;
    m_currentAdmin.email = email;

    // 调用 AdmSql 更改密码和管理员信息的方法
    if (m_admSql->changePassword(m_currentAdmin.aid, oldPassword, newPassword) &&
        m_admSql->updateAdminInfo(m_currentAdmin)) {
        QMessageBox::information(this, tr("成功"), tr("更新管理员信息成功！"));
        emit adminInfoChanged(m_currentAdmin); // 发送信号通知主窗口更新信息
        this->accept(); // 关闭对话框并返回 Accepted
    } else {
        QMessageBox::critical(this, tr("失败"), tr("更新管理员信息失败！旧密码输入错误！"));
    }
}

void Dialog_password::on_pb_cel_2_clicked()
{
    this->hide();
}

